package com.lgh.ibs.plugins.views;

import java.io.File;
import java.util.List;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.lgh.ibs.entity.MavenPom;
import com.lgh.ibs.log.IbsLogger;
import com.lgh.ibs.plugins.views.handler.ProjectImpHandler;
import com.lgh.ibs.utils.MavenPomUtil;
import com.lgh.ibs.utils.ProjectFileUtil;
import com.lgh.ibs.utils.SVNOptionUtil;

public class ProjectImpView extends ViewPart {
	public static final String ID = "com.lgh.ibs.plugins.views.projectImpView"; //$NON-NLS-1$
	private Text svnText;
	private Text wokespaceText;
	private Text projectText;
	private Table table;

	public ProjectImpView() {
	}

	/**
	 * Create contents of the view part.
	 * @param parent
	 */
	public void createPartControl(final Composite container) {
//		final Composite container = new Composite(parent, SWT.NONE);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);
		//项目名称
		/*Label projectLabel = new Label(container, SWT.CENTER);
		projectLabel.setText("项目名称: ");
		GridData gd_project = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
		gd_project.heightHint = 30;
		gd_project.widthHint = 120;
		projectLabel.setLayoutData(gd_project);
		
		projectText = new Text(container, SWT.BORDER);
		GridData gd_project_text = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_project_text.heightHint = 25;
		gd_project_text.horizontalSpan = 2;
		projectText.setLayoutData(gd_project_text);
		*/
		//svn目录
		Label svnLabel = new Label(container, SWT.CENTER);
		GridData gridData_svnLable = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
		gridData_svnLable.widthHint = 120;
		svnLabel.setText("SVN路径 URL: ");
		svnLabel.setLayoutData(gridData_svnLable);
		
		svnText = new Text(container, SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.CANCEL);
		GridData gd_svnText = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		// GridData的组件占两列显示
		gd_svnText.horizontalSpan = 2;
		gd_svnText.heightHint = 68;
		svnText.setLayoutData(gd_svnText);
		
		//工作空间输出目录
		Label workspaceOutDirLabel = new Label(container, SWT.CENTER);
		GridData gridData_workspaceOutDirLable = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
		gridData_workspaceOutDirLable.heightHint = 30;
		workspaceOutDirLabel.setText("输出目录: ");
		gridData_workspaceOutDirLable.widthHint = 120;
		workspaceOutDirLabel.setLayoutData(gridData_workspaceOutDirLable);
		
		wokespaceText = new Text(container, SWT.BORDER);
		GridData gd_text_1_1 = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_text_1_1.heightHint = 25;
		wokespaceText.setLayoutData(gd_text_1_1);
		String locationWorkSpace = Platform.getInstanceLocation().getURL().getPath();
		if(locationWorkSpace.startsWith("/")){
			locationWorkSpace = locationWorkSpace.substring(1, locationWorkSpace.length());
		}
		wokespaceText.setText(locationWorkSpace);
//		PlatformUI.getWorkbench().getw
		Button btnNewButton = new Button(container, SWT.NONE);
		btnNewButton.setText(" 浏览  ");
		// 添加按钮的选择事件
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				Shell shell = container.getShell();
				/*
				String fileName = new FileDialog(shell).open();
				if (fileName != null) {
					text.setText(fileName); 
				}*/
				//新建文件夹（目录）对话框
				DirectoryDialog folderdlg = new DirectoryDialog(shell);
				//设置文件对话框的标题
				folderdlg.setText("选择文件");
				//设置初始路径
				folderdlg.setFilterPath("SystemDrive");
				//设置对话框提示文本信息
				folderdlg.setMessage("请选择相应的文件夹");
				//打开文件对话框，返回选中文件夹目录
				String selecteddir=folderdlg.open();
				if(selecteddir==null){
					return ;
				}
				else{
					wokespaceText.setText(selecteddir);
					IbsLogger.INFO("您选中的文件夹目录为: "+selecteddir);
				}
				
			}
		});
		
		
		
		Button button = new Button(container, SWT.NONE);
		button.setText(" 导  入 ");
		
		ProgressBar progressBar = new ProgressBar(container, SWT.HORIZONTAL | SWT.INDETERMINATE);
		GridData gd_progressBar = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
		// GridData的组件占两列显示
		gd_progressBar.horizontalSpan = 2;
		progressBar.setLayoutData(gd_progressBar);
		
		createAndRsfushTable(container);
		createActions();
		initializeToolBar();
		initializeMenu();
		bandProjectImpData(button,container, progressBar);
	}

	private void createAndRsfushTable(final Composite container) {
		table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
		GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_table.horizontalSpan = 3;
		table.setLayoutData(gd_table);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		String[] colNames = new String[] { "工程名称", "版本", "root版本", "SVN URL" };
		TableColumn tcName = new TableColumn(table, SWT.LEFT);
		tcName.setText(colNames[0]);
		TableColumn tcAftifact = new TableColumn(table, SWT.NULL);
		tcAftifact.setText(colNames[1]);
		TableColumn tcVersionNumber = new TableColumn(table, SWT.NULL);
		tcVersionNumber.setText(colNames[2]);
		TableColumn tcSvnUrl = new TableColumn(table, SWT.NULL);
		tcSvnUrl.setText(colNames[3]);
		tcName.setWidth(200);
		tcAftifact.setWidth(200);
		tcVersionNumber.setWidth(160);
		tcSvnUrl.setWidth(500);
	}
	
	/**
	 * @Title: bandProjectImpData 
	 * @Description:绑定项目数据 
	 * @param button
	 * @param container
	 * @param progressBar 
	 * @throws 
	 * @author guohao.li
	 * @dateTime 2016年12月22日 下午3:38:34
	 */
	private void bandProjectImpData(Button button, final Composite container, final ProgressBar progressBar){
		
		button.addSelectionListener(new SelectionAdapter() {
			
			public void widgetSelected(SelectionEvent e) {
				(new IncresingOperator(progressBar, container)).start();
			}
		});
		
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar.
	 */
	private void initializeToolBar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars()
				.getToolBarManager();
	}

	/**
	 * Initialize the menu.
	 */
	private void initializeMenu() {
		IMenuManager menuManager = getViewSite().getActionBars()
				.getMenuManager();
	}

	public void setFocus() {
	}
	class IncresingOperator extends Thread {
		Composite  container;
		ProgressBar progressBar;
		IncresingOperator(ProgressBar progressBar, Composite  container) {
			this.progressBar = progressBar;
			this.container = container;
			
		}
		
		public void run() {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					int progressMaxVal = 0;
					Shell shell = container.getShell();
					//项目输出目录
					String projectPath = wokespaceText.getText();
					//svn路径逗号分隔串
					String svnPaths = svnText.getText();
					if(projectPath == null || projectPath == ""){
						MessageDialog.openInformation(shell, "warning","项目输出目录不能为空");
						return ;
					}
					if(svnPaths == null || svnPaths == ""){
						MessageDialog.openInformation(shell, "warning", "SVN分支URL不能为空！");
						return ;
					}
					
					//获取数据，显示导入的项目信息
					File filePath = new File(projectPath);
					if(!filePath.exists()){
						filePath.mkdirs();
					}
					//从SVN将项目checkOut到输出目录
					List<String> svnUrlList = ProjectImpHandler.getSvnUrlList(svnPaths);
					try {
						progressBar.setMinimum(0);
						progressMaxVal = svnUrlList.size();
						progressBar.setMaximum(progressMaxVal);
						SVNOptionUtil.checkOut(svnUrlList, projectPath, progressBar);
					} catch (Exception ex) {
						ex.printStackTrace();
						MessageDialog.openInformation(shell, "warning","SVNCheckOut error！"+ ex.getMessage());
						return ;
					}
//					createAndRsfushTable(container);
//					List<String[]> tableItemData = new ArrayList<String[]>();
					//workspace中的Maven 项目的pom文件集合
					table.clearAll();
					table.removeAll();
					List<String> projectPomFilePathList = ProjectFileUtil.getProjectDir(projectPath);
					for (int i = 0; i < projectPomFilePathList.size(); i++) {
						String pomFilePath = projectPomFilePathList.get(i);
						MavenPom mavenPom = null;
						try {
							mavenPom = MavenPomUtil.getMavenPom(pomFilePath);
						} catch (Exception e1) {
							e1.printStackTrace();
							IbsLogger.ERROR("获取pom.xml信息出错！", e1);
							MessageDialog.openInformation(shell, "warning","get pom.xml error！"+ e1.getMessage());
							return ;
						}
						//将检出的项目信息显示在table上
						//这里的项目名称和ArtifactId相同，pom文件中的name标签可能不存在，但ArtifactId一定存在
						String projectName = mavenPom.getProjectArtifactId();
						String projectVersion = mavenPom.getProjectVersion();
						String parentVersion = mavenPom.getParentVersion();
						String urlSvn = ProjectImpHandler.getSvnPath(projectName, svnUrlList);
						
//						tableItemData.add(new String[] { projectName, projectVersion, parentVersion, urlSvn });
						TableItem item = new TableItem(table, SWT.NONE);
						item.setText(new String[] { projectName, projectVersion, parentVersion, urlSvn });
					}
					progressBar.setSelection(progressMaxVal);
					MessageDialog.openInformation(shell, "成功", "项目checkOut到指定workspace成功！请在 file 菜单栏 使用import功能批量导入");
				}
			});
		}
	}
}
